package org.academic.texteditor.gui.component.listener;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JButton;
import javax.swing.JToolBar;

import org.academic.texteditor.gui.component.PageContainer;
import org.academic.texteditor.gui.component.toolbar.ToolBarFactory;
import org.academic.texteditor.gui.helper.ClipboardManager;
import org.academic.texteditor.gui.helper.DocumentManager;
import org.academic.texteditor.gui.plugin.text.PasteTextPlugin;

public class DropPasteTextListener implements DropTargetListener {

	public DropPasteTextListener() {

	}

	@Override
	public void dragEnter(DropTargetDragEvent event) {

	}

	@Override
	public void dragExit(DropTargetEvent dte) {

	}

	@Override
	public void dragOver(DropTargetDragEvent event) {

	}

	@Override
	public void drop(DropTargetDropEvent e) {
		try {
			Transferable t = e.getTransferable();

			if (e.isDataFlavorSupported(DataFlavor.stringFlavor)) {
				e.acceptDrop(e.getDropAction());

				String text = (String) t.getTransferData(ParagraphTransferable.paragraphFlavor);

				final JToolBar clipBoard = ToolBarFactory.getClipBoard();
				int count = clipBoard.getComponentCount();

				PageContainer document = DocumentManager.getInstance().getDocument();
				
				PasteTextPlugin plugin = new PasteTextPlugin(text);
				plugin.initialize(document);
				
				ClipboardManager.getInstance().copy(text);
				
				final JButton button = ToolBarFactory.createButton(clipBoard, "copy" + count, count, "", "images/copy-icon.png", plugin);
				button.setToolTipText(text);
				button.addMouseListener(new MouseListener(){
					@Override
					public void mouseClicked(MouseEvent e) {
						if (e.getButton() == MouseEvent.BUTTON3) {
							ClipboardManager.getInstance().remove(button.getToolTipText());
							ToolBarFactory.removeButton(clipBoard, button.getName());
						}
					}
					@Override
					public void mouseEntered(MouseEvent e) {
						
					}
					@Override
					public void mouseExited(MouseEvent e) {
						
					}
					@Override
					public void mousePressed(MouseEvent e) {
						
					}
					@Override
					public void mouseReleased(MouseEvent e) {
						
					}
				});
				e.dropComplete(true);
			} else {
				e.rejectDrop();
			}
		} catch (java.io.IOException e2) {
			e2.printStackTrace();
		} catch (UnsupportedFlavorException e2) {
			e2.printStackTrace();
		}
	}

	@Override
	public void dropActionChanged(DropTargetDragEvent dtde) {

	}

}
